from flask import Flask, jsonify, request
import os
import logging

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('/var/log/app.log'),
        logging.StreamHandler()
    ]
)

class HttpServer:
    def __init__(self, root_dir='/media/sdcard', on_push=None, on_stop=None):
        """
        初始化HTTP服务器
        :param root_dir: 根目录路径
        :param on_push: 推流回调函数，接收文件路径参数
        :param on_stop: 停止推流回调函数
        """
        self.app = Flask(__name__)
        self.ROOT_DIR = root_dir
        self.on_push = on_push
        self.on_stop = on_stop
        self._setup_routes()

    def _setup_routes(self):
        """设置路由"""
        @self.app.route('/api/list')
        def list_files():
            """获取指定目录下的文件和文件夹列表"""
            try:
                full_path = request.args.get('dir', '')
                
                # 安全检查：确保路径在ROOT_DIR下
                if not full_path.startswith(self.ROOT_DIR):
                    return jsonify({'error': '访问被拒绝'}), 403
                    
                if not os.path.exists(full_path):
                    return jsonify({'error': '目录不存在'}), 404
                    
                items = os.listdir(full_path)
                folders = []
                files = []
                
                for item in items:
                    item_path = os.path.join(full_path, item)
                    if os.path.isdir(item_path):
                        folders.append({'name': item})
                    elif item.lower().endswith('.mp4'):
                        files.append({'name': item})
                        
                return jsonify({
                    'folders': folders,
                    'files': files
                })
                
            except Exception as e:
                logging.error(f"获取文件列表失败: {e}")
                return jsonify({'error': str(e)}), 500

        @self.app.route('/api/push', methods=['POST'])
        def push_stream():
            """处理推流请求"""
            try:
                full_path = request.args.get('path', '')
                if not full_path:
                    return jsonify({'success': False, 'message': '未指定文件路径'}), 400
                
                # 安全检查：确保路径在ROOT_DIR下
                if not full_path.startswith(self.ROOT_DIR):
                    return jsonify({'success': False, 'message': '访问被拒绝'}), 403
                    
                if not os.path.exists(full_path):
                    return jsonify({'success': False, 'message': '文件不存在'}), 404
                    
                # 调用推流回调函数
                if self.on_push:
                    self.on_push(full_path)
                    return jsonify({'success': True, 'message': '推流请求已发送'})
                else:
                    return jsonify({'success': False, 'message': '推流功能未启用'}), 500
                    
            except Exception as e:
                logging.error(f"处理推流请求失败: {e}")
                return jsonify({'success': False, 'message': str(e)}), 500

        @self.app.route('/api/stop', methods=['POST'])
        def stop_stream():
            """停止推流"""
            try:
                full_path = request.args.get('path', '')
                if not full_path:
                    return jsonify({'success': False, 'message': '未指定文件路径'}), 400
                
                # 安全检查：确保路径在ROOT_DIR下
                if not full_path.startswith(self.ROOT_DIR):
                    return jsonify({'success': False, 'message': '访问被拒绝'}), 403
                    
                if self.on_stop:
                    self.on_stop(full_path)
                    return jsonify({'success': True, 'message': '停止推流请求已发送'})
                else:
                    return jsonify({'success': False, 'message': '推流功能未启用'}), 500
            except Exception as e:
                logging.error(f"处理停止推流请求失败: {e}")
                return jsonify({'success': False, 'message': str(e)}), 500

    def run(self, host='0.0.0.0', port=5000):
        """运行HTTP服务器"""
        self.app.run(host=host, port=port)

# 如果直接运行此文件，则启动服务器
if __name__ == '__main__':
    server = HttpServer()
    server.run()